package com.chenailin.www.util;

import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.Optional;

public class SafeUtil {
    // 安全字符串转整数
    public static Optional<Integer> safeStringToInt(String input) {
        if (input == null || input.trim().isEmpty()) return Optional.empty();
        try {
            return Optional.of(Integer.parseInt(input.trim()));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }

    // 安全除法
    public static Optional<Double> safeDivide(double a, double b) {
        return (b == 0) ? Optional.empty() : Optional.of(a / b);
    }

    // 安全获取数组元素
    public static <T> Optional<T> safeGetElement(T[] array, int index) {
        if (array == null || index < 0 || index >= array.length) {
            return Optional.empty();
        }
        return Optional.of(array[index]);
    }

    // 安全解析日期
    public static Optional<LocalDate> safeParseDate(String dateStr) {
        if (dateStr == null) return Optional.empty();
        try {
            return Optional.of(LocalDate.parse(dateStr));
        } catch (DateTimeParseException e) {
            return Optional.empty();
        }
    }

    // 安全处理空指针
    public static String safeToString(Object obj) {
        return (obj != null) ? obj.toString() : "[NULL]";
    }

    // 安全执行代码块
    public static void safeExecute(Runnable code) {
        try {
            code.run();
        } catch (Exception e) {
            System.err.println("执行失败: " + e.getMessage());
        }
    }
}
